package com.ton.common.controller.task;

import com.ton.common.entity.TonPayOrder;
import com.ton.common.service.PayOrderService;
import com.ton.config.NetContext;
import com.ton.utils.LoopThread;
import com.ton.utils.http.RestTemplateUtils;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;

/**
 * 支付订单任务类
 */
@Slf4j
public class PayOrderPayingTask extends LoopThread {
    public static final long ORDER_QUERY_WAIT_TIME = 10000;
    ScheduledExecutorService executor = Executors.newScheduledThreadPool(5);

    @Getter
    private static Map<Long, PayOrderTrans> orderMap = new ConcurrentHashMap<>();

    /**
     * 传递一个payOrderTrans 添加任务
     *
     * @param payOrderTrans 订单封装对象
     */
    public static void addOrder(PayOrderTrans payOrderTrans) {
        orderMap.put(payOrderTrans.getOrderId(), payOrderTrans);
    }

    /**
     * 根据ID查找一个订单任务
     *
     * @param id 订单ID
     */
    public static TonPayOrder getOrderById(Long id) {
        PayOrderTrans trans = orderMap.get(id);
        if (Objects.isNull(trans)) {
            return null;
        }

        TonPayOrder tonPayOrder = trans.getTonPayOrder();
        return tonPayOrder;
    }

    /**
     * 删除订单任务
     *
     * @param id 订单id
     */
    public static void deleteOrder(Long id) {
        orderMap.remove(id);
    }

    /**
     * 获取任务的过期时间
     *
     * @param id 订单id
     * @return 过期时间 /秒
     */
    public static Long getExpired(Long id) {
        PayOrderTrans trans = orderMap.get(id);
        if (Objects.isNull(trans)) {
            return -1L;
        }
        TonPayOrder tonPayOrder = trans.getTonPayOrder();
        long now = System.currentTimeMillis();
        long t = tonPayOrder.getCreateTime().getTime() + 1000L * 60 * 10;
        if (now > t) {
            return -1L;
        }
        if ((t - now) / 1000 == 0) {
            return -1L;
        }

        return (t - now) / 1000;
    }

    /**
     * 启动初始化
     *
     * @return
     */
    public PayOrderPayingTask init() {
        System.out.println("启动初始化！！");
        PayOrderService PayOrderService = NetContext.getInstance(PayOrderService.class);
        List<TonPayOrder> tonPayOrders = PayOrderService.getUndonePayOrder();
        for (TonPayOrder order : tonPayOrders) {
            PayOrderTrans from = PayOrderTrans.createFrom(order);
            orderMap.put(order.getId(), from);
        }
        return this;
    }

    @Override
    public long getLoopTime() {
        return 2000;
    }

    @Override
    public void execute() throws Exception {
        // System.out.println("正在执行---->>>初始化！！");
        long now = System.currentTimeMillis();
        for (PayOrderTrans order : orderMap.values()) {
            // 终止条件
            if (order.isListenTimeOut(now)) {
                orderMap.remove(order.getOrderId());
                PayOrderService PayOrderService = NetContext.getInstance(PayOrderService.class);
                //TronAccountService tronAccountService = NetContext.getInstance(TronAccountService.class);

                //PayOrderService.updateFailStatus(order.getPayOrder(), tronAccountService);

                TonPayOrder tonPayOrder = order.getTonPayOrder();
                if (order.getTonPayOrder().getCallbackUrl().contains("http")) {
                    HashMap<String, Object> params = new HashMap<>();
                    params.put("orderId", order.getTonPayOrder().getId()); //商户订单号
                    params.put("merchantOrderId", tonPayOrder.getMerchantOrderId()); //商家订单号
                    params.put("amount", tonPayOrder.getAmount()); //支付金额
                    params.put("appId", tonPayOrder.getAppId()); //appid
                    params.put("bankMsg", ""); //信息
                    params.put("time", new Date().getTime()); //订单创建时间
                    params.put("coinType", tonPayOrder.getCoinType()); //货币类型
                    params.put("remark", tonPayOrder.getRemark()); //备注
                    params.put("status", -1); //失败
                    String doPost = RestTemplateUtils.doPost(tonPayOrder.getCallbackUrl(), new HashMap<>(), params);
                    
                    log.info("完成支付回调！！");
                }

                continue;
            }
            if (order.isSyncMoneyWorking()) {
                continue;
            }
            if (now > order.getExecutetime()) {
                order.setExecutetime(now + ORDER_QUERY_WAIT_TIME);
                executor.submit(() -> {
                    order.listenTans(order.getTonPayOrder());
                });
            }

        }
    }

}
